﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TallyJ1Announcer
{
	public static class Extensions
	{
		///<summary>Get all exception messages</summary>
		///<param name="input"></param>
		///<param name="seperator"></param>
		///<returns></returns>
		public static string AllMessages(this Exception input, string seperator = "\n")
		{
			if (input == null)
			{
				return string.Empty;
			}

			var messages = new List<string>();
			while (input != null)
			{
				messages.Add(input.Message);
				input = input.InnerException;
			}
			return messages.Joined(seperator);
		}

		/// <summary>Returns a string with all the items concatenated together, joined with ; </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public static string Joined(this IEnumerable<string> input)
		{
			return input.Joined("; ");
		}

		/// <summary>Returns a string with all the items concatenated together.</summary>
		///<param name="input"></param>
		///<param name="seperator"></param>
		///<returns></returns>
		public static string Joined(this IEnumerable<string> input, string seperator)
		{
			if (input == null || input.Count() == 0)
			{
				return string.Empty;
			}

			return String.Join(seperator, input.ToArray());
		}

		///<summary>Return the input string. However, if it is null or empty, return the default value</summary>
		///<param name="input"></param>
		///<param name="defaultValue"></param>
		///<returns></returns>
		public static string DefaultingTo(this string input, string defaultValue)
		{
			return input.HasContent() ? input : defaultValue;
		}

		///<summary>Determine if this string is empty (is null or empty)</summary>
		public static bool HasNoContent(this string input)
		{
			return string.IsNullOrEmpty(input);
		}

		///<summary>Determine if this string has content (is not null or empty)</summary>
		///<param name="input"></param>
		///<returns></returns>
		public static bool HasContent(this string input)
		{
			return !string.IsNullOrEmpty(input);
		}

		public static int AsInt(this object input)
		{
			if (input != null)
			{
				int result;
				if (Int32.TryParse(input.ToString(), out result))
				{
					return result;
				}
			}
			return 0;
		}


	}
}